package com.webcamtracker.video;

import com.webcamtracker.image.ImageProvider;

import javax.media.Buffer;
import javax.media.Manager;
import javax.media.NoDataSourceException;
import javax.media.Player;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

public class VideoImageProvider
        implements ImageProvider {
    //~ Instance fields ......................................................................................

    private FrameGrabbingControl frameGrabber;
    private String path;
    private Player player;

    //~ Constructors .........................................................................................

    public VideoImageProvider(String url) {
        this.path = url;
    }

    //~ Methods ..............................................................................................

    public Player getPlayer() {
        return player;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public void init()
            throws NoDataSourceException, IOException {
        URL vurl;

        try {
            System.out.println("path = " + path);
            if ((vurl = new URL(path)) == null) {
                System.out.println("Can't build URL for " + path);
                return;
            }

            player = Manager.createPlayer(vurl);
            player.start();
            player.realize();
            Thread.sleep(1000);
            frameGrabber =
                    (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public BufferedImage getImage() {
        Buffer buf = frameGrabber.grabFrame();

        // Convert frame to an buffered image and return
        Image img = (new BufferToImage((VideoFormat) buf.getFormat()).createImage(buf));
        BufferedImage buffImg =
                new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D g = buffImg.createGraphics();
        g.drawImage(img, null, null);
        return buffImg;
    }
}
